<!-- 块设备 -->
<template>
  <a-row>
    <a-row class='mytitle'>
      <!-- <a-icon :component="net" style="margin:0 .5rem 0 0"/> -->
      {{ $t('Block') }}
      <!-- {{$t('Network-disk')}} -->
    </a-row>
    <a-card hoverable style="margin:1em" v-userAuth="'D3'">
      <a-tabs :defaultActiveKey="defaultActiveKey" @change="tabsChange">
        <!-- 导出报表 -->
        <a-button v-userAuth="'D23-2'" v-if="currentTabKey == 'overview'" slot="tabBarExtraContent" type="primary"
          @click="exportReport" :loading="loadingExport" :class="loadingExport ? 'export-btn' : ''">
          <!-- <i class="icon icon-export16f export-icon"></i> -->

          <Iconfont class="icon export-icon" type="icon-export16f"></Iconfont>
          {{ $t('Export-report') }}
        </a-button>
        <!-- 概况 -->
        <a-tab-pane :tab="$t('Overview')" key="overview">
          <NoAuthPage v-showNoAuth="'D23-1'" :imgBoxStyle="{ height: '71vh', margin: 0 }" />

          <BlockOverview v-if="authArr.indexOf('overview') !== -1 && currentTabKey == 'overview'" />
        </a-tab-pane>
        <a-tab-pane :tab="$t('Block')" key='block'>
          <!-- v-userAuth="'D4'" -->
          <!-- 块设备 -->
          <a-card v-if="currentTabKey == 'block'">
            <NoAuthPage v-showNoAuth="'D4-1'" :imgBoxStyle="{ height: '40vh', margin: 0 }" />

            <div style="margin:0 0 1em 0 ">
              <a-button v-userAuth="'D4-2'" type="primary" @click="create = true" style="margin-right:10px">
                <!-- <i class="icon icon-new16f out-operation-icon"></i> -->
                <Iconfont class="icon out-operation-icon" type="icon-new16f"></Iconfont>
                <span>{{ $t('Add-new') }}</span>
              </a-button>
              <!-- 导入 -->
              <!-- <a-button @click="handleImportBlock">
              <i class="icon icon-import16f out-operation-icon"></i>
              <span>{{$t('Import')}}</span>
            </a-button> -->

              <!-- <a-tooltip placement='bottom' v-userAuth="'D4-2'">
              <template slot='title'>
                <span>{{$t('Create')}}</span>
              </template>
<a-button type="primary" icon='file-add' @click="create = true"></a-button>
</a-tooltip> -->
              <!-- <a-tooltip placement='bottom' v-userAuth="'D4-7'">
              <template slot='title'>
                <span>{{$t('Edit')}}</span>
              </template>
              <a-button :disabled="selectedRowKeys.length==0" type='primary' style="margin-left:1em" icon='form' @click="openmodal('modify')"></a-button>
            </a-tooltip>
            <a-tooltip placement='bottom' v-userAuth="'D4-3'">
                <template slot='title'>
                    <span>{{$t('Copy')}}</span>
                </template>
                <a-button :disabled="selectedRowKeys.length==0" type='primary' style="margin-left:1em" icon='copy' @click="openmodal('copy')"></a-button>
            </a-tooltip>
            <a-tooltip placement='bottom' v-userAuth="'D4-4'">
                <template slot='title'>
                    <span>{{$t('Detach')}}</span>
                </template>
                <a-button :disabled="selectedRowKeys.length==0" type='primary' style="margin-left:1em" icon='link' @click="openmodal('detach')"></a-button>
            </a-tooltip>
            <a-tooltip placement='bottom' v-userAuth="'D4-5'">
                <template slot='title'>
                    <span>{{$t('Delete')}}</span>
                </template>
                <a-button :disabled="selectedRowKeys.length==0" type='danger' style="margin-left:1em" icon='close-circle' @click="openmodal('delosd')"></a-button>
            </a-tooltip>
            <a-tooltip placement='bottom' v-userAuth="'D4-6'">
                <template slot='title'>
                    <span>{{$t('to-Recycle-bin')}}</span>
                </template>
                <a-button :disabled="selectedRowKeys.length==0" type='danger' style="margin-left:1em" icon='delete' @click="openmodal('trash')"></a-button>
            </a-tooltip> -->
            </div>
            <!-- :rowSelection='{type:"radio",selectedRowKeys:selectedRowKeys,onChange:onSelectChange,onSelect:onSelect}'  -->
            <a-table class="tabstyle" :columns="osdcolumns" :loading="loading" :dataSource="this.$store.state.blockdata"
              size="small" rowKey='id' :pagination='pagination' :locale="defaultSetting" bordered
              :rowClassName="(record, i) => i % 2 === 1 ? 'table-even-row' : 'table-odd-row'" :components='components'>
              <!-- :scroll="{ x: 1500 }" -->
              <span slot="status" slot-scope='status'>
                <div v-if="status">
                  <span class="green-circle"></span><span>{{ $t('Connected') }}</span>
                </div>
                <div v-else>
                  <span class="orange-circle"></span><span>{{ $t('Not-connected') }}</span>
                </div>
                <!-- <span v-if="status == 'normal'" >
                  <span class="green-circle"></span><span>{{$t('Actionable')}}</span>
                  <a-tag color="green">{{$t('Actionable')}}</a-tag>注释
                </span>
                <span v-if="status == 'link'" >
                  <span class="orange-circle"></span><span>{{$t('Connecting')}}</span>
                  <a-tag color="orange">{{$t('Connecting')}}</a-tag>注释
                </span>
                <span v-if="status == 'copy'" >
                  <span class="orange-circle"></span><span>{{$t('Copying')}}</span>
                  <a-tag color="orange">{{$t('Copying')}}</a-tag>注释
                </span>
                <span v-if="status == 'rollback'" >
                  <span class="orange-circle"></span><span>{{$t('Rolling-back')}}</span>
                  <a-tag color="orange">{{$t('Rolling-back')}}</a-tag>注释
                </span>
                <span v-if="status == 'lun'" >
                  <span class="orange-circle"></span><span>lun</span>
                  <a-tag color="orange" style="padding:0 1.3em">lun</a-tag>注释
                </span>
                <span v-if="status == 'clone'" >
                  <span class="orange-circle"></span><span>{{$t('Cloning')}}</span>
                  <a-tag color="orange">{{$t('Cloning')}}</a-tag>注释
                </span>
                <span v-if="status == 'flatten'" >
                  <span class="orange-circle"></span><span>{{$t('Separating')}}</span>
                  <a-tag color="orange">{{$t('Separating')}}</a-tag>注释
                </span> -->
                <!-- <span v-else >{{status}} 
                  <a-spin>
                    <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
                  </a-spin>
                </span> -->
              </span>
              <template slot="parent" slot-scope='text, record'>
                <span v-if="text != ''">{{ text }}</span>
                <span v-else>-</span>
              </template>

              <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                class='custom-filter-dropdown'>
                <a-input v-ant-ref="c => searchInput = c" :placeholder="$t('Enter') + $t('Search-content')"
                  :value="selectedKeys[0]" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                  @pressEnter="() => handleSearch(selectedKeys, confirm)"
                  style="width: 188px; margin-bottom: 8px; display: block;" />
                <a-button type='primary' @click="() => handleSearch(selectedKeys, confirm)" icon="search" size="small"
                  style="width: 90px; margin-right: 8px">{{ $t('Search') }}</a-button>
                <a-button @click="() => handleReset(clearFilters)" size="small" style="width: 90px">{{ $t('Reset')
                  }}</a-button>
              </div>
              <a-icon slot="filterIcon" slot-scope="filtered" type='search'
                :style="{ color: filtered ? '#108ee9' : undefined }" />
              <!-- 块设备名 -->
              <template slot="customRender" slot-scope="text, record">
                <a-tooltip>
                  <template slot="title">
                    <span>{{ record.name }}</span>
                  </template>
                  <div>
                    <span v-if='searchText'>
                      <template
                        v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))">
                        <mark v-if="fragment.toLowerCase() === searchText.toLowerCase()" :key="i"
                          class="highlight jump-text" @click="showBlockDetail(record)">{{ fragment }}</mark>
                        <template v-else>
                          <span :key="i" @click="showBlockDetail(record)" class="jump-text">{{ fragment }}</span>
                        </template>
                      </template>
                    </span>
                    <template v-else>
                      <span @click="showBlockDetail(record)" class="jump-text">{{ text }}</span>
                    </template>
                  </div>
                </a-tooltip>
              </template>
              <!-- 实际使用量 -->
              <template slot='usageTitle'>
                <span :title="$t('Actual-usage')">{{ $t('Actual-usage') }}</span>
                <a-tooltip>
                  <template slot="title">
                    <span v-if="$store.state.language === 'zh'">此块设备和其所有快照，合计占用的容量</span>
                    <span v-else>The total capacity occupied by this device and all its snapshots</span>
                  </template>
                  <i style="color:grey" class="icon icon-a-16_f_ic_about"></i>
                </a-tooltip>
              </template>
              <!-- 操作列 -->
              <template slot="action" slot-scope="text, record">
                <div v-userAuth="'D4-1'">
                  <a-tooltip placement='top' v-userAuth="'D4-7'">
                    <template slot='title'>
                      <span>{{ $t('Edit') }}</span>
                    </template>
                    <!-- <i 
                    class="icon icon-edit16f table-operation-icon"
                    @click="openmodal('modify', record)"
                  ></i> -->

                    <Iconfont class="icon table-operation-icon" type="icon-edit16f"
                      @click="openmodal('modify', record)">
                    </Iconfont>
                  </a-tooltip>
                  <a-tooltip placement='top' v-userAuth="'D4-3'">
                    <template slot='title'>
                      <span>{{ $t('Copy') }}</span>
                    </template>
                    <!-- <i 
                    class="icon icon-copy16f table-operation-icon"
                    @click="openmodal('copy', record)"
                  ></i> -->
                    <Iconfont class="icon table-operation-icon" type="icon-copy16f" @click="openmodal('copy', record)">
                    </Iconfont>
                  </a-tooltip>
                  <a-dropdown>
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                      <!-- <i class="icon icon-more16f table-operation-icon"></i> -->
                      <Iconfont class="icon table-operation-icon" type="icon-more16f"></Iconfont>
                    </a>
                    <a-menu slot="overlay">
                      <!-- 分离 -->
                      <a-menu-item v-userAuth="'D4-4'" @click="openmodal('detach', record)">
                        <!-- <i class="icon icon-break16f menu-item-icon"></i> -->
                        <Iconfont class="icon menu-item-icon" type="icon-break16f"></Iconfont>
                        <span>{{ $t('Detach') }}</span>
                      </a-menu-item>
                      <!-- 放至回收站 -->
                      <a-menu-item v-userAuth="'D4-6'" @click="openmodal('trash', record)">
                        <!-- <i class="icon icon-recycle16f menu-item-icon"></i> -->
                        <Iconfont class="icon menu-item-icon" type="icon-recycle16f"></Iconfont>
                        <span>{{ $t('to-Recycle-bin') }}</span>
                      </a-menu-item>
                      <!-- 删除 -->
                      <a-menu-item v-userAuth="'D4-5'" @click="openmodal('delosd', record)">
                        <!-- <i class="icon icon-delete16f menu-item-icon"></i> -->
                        <Iconfont class="icon menu-item-icon" type="icon-delete16f"></Iconfont>
                        <span>{{ $t('Delete') }}</span>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </div>
              </template>
            </a-table>
          </a-card>
        </a-tab-pane>
        <!-- 回收站 -->
        <a-tab-pane :tab="$t('Recycle-bin')" key='2'>
          <Recycle v-if="authArr.indexOf('2') !== -1 && currentTabKey == '2'" @omodal="resetflag" :flag="trashflag">
          </Recycle>
        </a-tab-pane>
        <!-- iscsi -->
        <a-tab-pane tab='iSCSI' key="iscsi">
          <!-- v-userAuth="'D7'" -->
          <NoAuthPage v-showNoAuth="['D7', 'D22']" :imgBoxStyle="{ height: '71vh', margin: 0 }" />

          <ISCSI v-if="authArr.indexOf('iscsi') !== -1 && currentTabKey == 'iscsi'"></ISCSI>
        </a-tab-pane>
        <!-- 优先级策略 -->
        <a-tab-pane :tab="$t('Priority-policy')" key='4'>
          <!-- v-userAuth="'D8'" -->
          <Policy v-if="authArr.indexOf('4') !== -1 && currentTabKey == '4'" />
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <!-- <a-row style="margin:1em" v-userAuth="'D3'">
    <a-card hoverable>
      <a-tabs defaultActiveKey='1' >
        <a-tab-pane :tab="$t('Snap')" key='1'>
          <Snap class="tabs-top"></Snap>  -->
    <!-- :blockname='blockId' :poolname='pool' -->
    </a-tab-pane>
    <!-- <a-tab-pane tab='iSCSI' key='2'>
          <ISCSI class="tabs-top"></ISCSI>
        </a-tab-pane> -->
    <!-- <a-tab-pane :tab="$t('Recycle-bin')" key='3'> -->
    <!-- v-userAuth="'D6'" -->
    <!-- <Recycle class="tabs-top" @omodal='resetflag' :flag = 'trashflag'></Recycle> -->
    <!-- </a-tab-pane> -->
    <!-- </a-tabs>
    </a-card>
  </a-row> -->

    <Cosd :cc='create' @omodal='changemodal' :strategyData="strategyData"></Cosd>

    <Mosd :mm='modify' @omodal="changemodal" :tarname='onerecord' :strategyData="strategyData"></Mosd>

    <Copyosd :pp='copy' @omodal='changemodal' :tarname='onerecord'></Copyosd>
    <!-- 放至回收站 -->
    <a-modal :title="$t('to-Recycle-bin')" v-model='trash' @cancel='cancelhandle' width='35%' @ok='trashsub'
      :cancelText="$t('Cancel')" :okText="$t('Sure')" :maskClosable='false' v-dragModal>
      <a-spin size="large"
        style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%"
        tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
      <!-- <p>{{$t('Recycle-des')}}</p> -->
      <p>
        {{
          $store.state.language == 'zh' ? `若要将“${target}”移至回收站，您可以选择一个块设备日期，然后单击“确认”。`
            : `To move "${target}" to the Recycle Bin, you can select a block device date and click OK.`
        }}
      </p>
      <a-form :form='form'>
        <a-form-item :label="$t('Select-time')" v-bind="formlayout">
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' :placeholder="$t('Select-date-picker')"
            @change="Changedate" v-decorator="['datetime', {
              rules: [{ required: true, message: $t('Select-time') }]
            }]" :locale="dateLocale">
          </a-date-picker>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 导出报表弹窗 -->
    <!-- <ExportReport 
    :visible="exportReportVisible"
    @closeExport="closeExport"
  /> -->

    <!-- 导入块设备弹窗 -->
    <ImportBlock :visible="importBlockVisible" @closeImport="closeImport" />

  </a-row>
</template>
<script>
// import Topbar from "../../../components/common/Topbar";
// import Menubar from "../../../components/common/Menubar";
import BlockOverview from '@/views/storage_mgr/osd/BlockOverview'
import Snap from '../../../components/storage_mgr/block/snap'
// import ISCSI from '../../../components/storage_mgr/block/iscsi'
import ISCSI from '@/views/storage_mgr/osd/iscsi/ISCSI'
import Policy from '@/components/storage_mgr/block/priorityPolicy/Policy'
import Recycle from '../../../components/storage_mgr/block/recycle'
// import net from '../../../../static/images/svg/ic_Networkdisk03.svg'
import Cosd from './osdopr/createosd'
import Mosd from './osdopr/modifyosd'
import Copyosd from './osdopr/copyosd'
import EmptyData from '@/components/common/EmptyData'
import NoAuthPage from '@/components/common/NoAuthPage'
// import ExportReport from '@/views/storage_mgr/osd/blockOperation/ExportReport'
import ImportBlock from '@/views/storage_mgr/osd/blockOperation/ImportBlock'

import { setTimeout } from 'timers';
import { sizeCompare, sortIp } from '@/assets/js/tableSortMethods'
import downloadFile from '@/assets/js/downloadFile'

import VueDraggableResizable from 'vue-draggable-resizable'

import request from '@/request/request'

export default {
  name: "Block",
  // Topbar, Menubar 
  components: {
    BlockOverview, ISCSI, Policy, Snap, Recycle, Cosd, Mosd, Copyosd,
    EmptyData, NoAuthPage,
    ImportBlock, VueDraggableResizable
  },
  // template: '<a-icon :component="net" />',
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props
          const col = this.osdcolumns.find((col) => {
            const k = col.dataIndex || col.key
            return k === key
          })
          if (!col || !col.width) {
            return h('th', { ...restProps }, [...children])
          }
          const dragProps = {
            key: col.dataIndex || col.key,
            class: 'table-draggable-handle',
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: 'x',
              draggable: true,
              resizable: false,
            },
            on: {
              dragging: (x, y) => {
                col.width = Math.max(x, 1)
              },
            },
          }
          const drag = h('vue-draggable-resizable', { ...dragProps })
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
        },
      },
    }

    return {
      // net,
      osdcolumns: [
        {
          title: this.$t('Block') + this.$t('Name'),
          dataIndex: "name",
          key: "name",
          ellipsis: true,
          sorter: (a, b) => a.name.length - b.name.length,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
          // fixed: 'left',
          width: this.$store.state.language == 'zh' ? 160 : 190
        },
        { title: this.$t('Pool') + this.$t('Name'), dataIndex: 'pool_name', key: 'pool_name', ellipsis: true, sorter: (a, b) => a.pool_name.length - b.pool_name.length, },
        // {title:this.$t('Dedicated'),dataIndex:'data_pool',key:'data_pool'},
        { title: this.$t('Capacity'), dataIndex: 'size', key: 'size', ellipsis: true, sorter: (a, b) => this.sizeCompare(a.size, b.size), },
        // 实际使用量
        { slots: { title: 'usageTitle' }, dataIndex: 'disk_usage', key: 'disk_usage', ellipsis: true, sorter: (a, b) => this.sizeCompare(a.disk_usage, b.disk_usage), },
        // {title:this.$t('Obj')+this.$t('Amount'),dataIndex:'num_objs',key:'num_objs',ellipsis: true,},
        // {title:this.$t('Object-size'),dataIndex:'obj_size',key:'obj_size',ellipsis: true},
        // {title:this.$t('Supply')+this.$t('Capacity'),dataIndex:'disk_usage',key:'disk_usage'},
        // {title:this.$t('Supply')+this.$t('Total-capacity'),dataIndex:'total_disk_usage',key:'total_disk_usage'},
        { title: this.$t('Parent-node'), dataIndex: 'parent', key: 'parent', ellipsis: true, scopedSlots: { customRender: 'parent' }, sorter: (a, b) => a.parent.length - b.parent.length, },
        // 锁拥有者
        // {title:this.$t('Lock-owner'), dataIndex:'ip_address', key:'ip_address', ellipsis: true, scopedSlots:{customRender:'ip_address'}, sorter:(a, b) => this.sortIp(a.ip_address, b.ip_address),},
        { title: this.$t('Status'), dataIndex: 'status', key: 'status', ellipsis: true, scopedSlots: { customRender: 'status' }, sorter: (a, b) => a.status.length - b.status.length, },
        { title: this.$t('Operate'), key: 'operation', width: 130, scopedSlots: { customRender: 'action' }, },// fixed: 'right', 
      ],
      create: false,
      modify: false,
      copy: false,
      trash: false,
      searchText: '',
      searchInput: null,
      form: this.$form.createForm(this),
      pagination: {
        defaultPageSize: 5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onChange: (page, pageSize) => { this.selectedRowKeys = []; this.target = ''; },
        buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
        // onShowSizeChange:(current, pageSize)=>this.pageSize = pageSize
      },
      formlayout: {
        labelCol: { span: 10 },
        wrapperCol: { span: 14 }
      },
      selectedRowKeys: [],
      blockdata: [],
      target: '',
      tarparent: '',
      pool: '',
      onerecord: {},
      delay: 0,
      showtime: '',
      num: 0,
      loading: true,
      trashflag: false,
      spinning: false,
      blockId: '',
      defaultSetting: { emptyText: <EmptyData /> },
      dateLocale: {
        lang: {
          placeholder: "Select date",
          rangePlaceholder: ["Start date", "End date"],
          today: "Today",
          now: this.$t('today'),
          backToToday: "Back to today",
          ok: this.$t('Sure'),
          clear: "Clear",
          month: "Month",
          year: "Year",
          timeSelect: this.$t('Select-time-picker'),
          dateSelect: this.$t('Select-date-picker'),
          monthSelect: "Choose a month",
          yearSelect: "Choose a year",
          decadeSelect: "Choose a decade",
          yearFormat: "YYYY",
          dateFormat: "M/D/YYYY",
          dayFormat: "D",
          dateTimeFormat: "M/D/YYYY HH:mm:ss",
          monthFormat: "MMMM",
          monthBeforeYear: true,
          previousMonth: "Previous month (PageUp)",
          nextMonth: "Next month (PageDown)",
          previousYear: "Last year (Control + left)",
          nextYear: "Next year (Control + right)",
          previousDecade: "Last decade",
          nextDecade: "Next decade",
          previousCentury: "Last century",
          nextCentury: "Next century"
        },
        timePickerLocale: {
          placeholder: "Select time"
        },
        dateFormat: "YYYY-MM-DD",
        dateTimeFormat: "YYYY-MM-DD HH:mm:ss",
        weekFormat: "YYYY-wo",
        monthFormat: "YYYY-MM"
      },
      defaultActiveKey: 'overview',
      currentTabKey: 'overview',
      // user_id: localStorage.getItem('user_id'),
      strategyData: [],
      exportReportVisible: false,
      importBlockVisible: false,
      loadingExport: false,
      authArr: []
    }
  },

  computed: {
    getblock() {
      return this.$store.state.baseblock
    },
    getblockdata() {
      return this.$store.state.blockdata
    },
    getlanguage() {
      return this.$store.state.language
    }
  },
  watch: {
    getlanguage(val) {  //监听语言切换，切换data组件内的多语言
      this.osdcolumns = [
        {
          title: this.$t('Block') + this.$t('Name'),
          dataIndex: "name",
          key: "name",
          ellipsis: true,
          sorter: (a, b) => a.name.length - b.name.length,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
          // fixed: 'left',
          width: val == 'zh' ? 120 : 190
        },
        { title: this.$t('Pool') + this.$t('Name'), dataIndex: 'pool_name', key: 'pool_name', ellipsis: true, },
        // {title:this.$t('Dedicated'),dataIndex:'data_pool',key:'data_pool'},
        { title: this.$t('Capacity'), dataIndex: 'size', key: 'size', ellipsis: true, sorter: (a, b) => this.sizeCompare(a.size, b.size), },
        { slots: { title: 'usageTitle' }, dataIndex: 'disk_usage', key: 'disk_usage', ellipsis: true, sorter: (a, b) => this.sizeCompare(a.disk_usage, b.disk_usage), },
        // {title:this.$t('Obj')+this.$t('Amount'),dataIndex:'num_objs',key:'num_objs',ellipsis: true,},
        // {title:this.$t('Object-size'),dataIndex:'obj_size',key:'obj_size',ellipsis: true},
        // {title:this.$t('Supply')+this.$t('Capacity'),dataIndex:'disk_usage',key:'disk_usage'},
        // {title:this.$t('Supply')+this.$t('Total-capacity'),dataIndex:'total_disk_usage',key:'total_disk_usage'},
        { title: this.$t('Parent-node'), dataIndex: 'parent', key: 'parent', ellipsis: true, scopedSlots: { customRender: 'parent' }, sorter: (a, b) => a.parent.length - b.parent.length, },
        // {title:this.$t('Lock-owner'), dataIndex:'ip_address', key:'ip_address', ellipsis: true, scopedSlots:{customRender:'ip_address'}, sorter:(a, b) => this.sortIp(a.ip_address, b.ip_address)},
        { title: this.$t('Status'), dataIndex: 'status', key: 'status', ellipsis: true, scopedSlots: { customRender: 'status' }, sorter: (a, b) => a.status.length - b.status.length, },
        { title: this.$t('Operate'), key: 'operation', width: 130, scopedSlots: { customRender: 'action' }, },// fixed: 'right', 
      ];
      this.dateLocale = {
        lang: {
          placeholder: "Select date",
          rangePlaceholder: ["Start date", "End date"],
          today: "Today",
          now: this.$t('today'),
          backToToday: "Back to today",
          ok: this.$t('Sure'),
          clear: "Clear",
          month: "Month",
          year: "Year",
          timeSelect: this.$t('Select-time-picker'),
          dateSelect: this.$t('Select-date-picker'),
          monthSelect: "Choose a month",
          yearSelect: "Choose a year",
          decadeSelect: "Choose a decade",
          yearFormat: "YYYY",
          dateFormat: "M/D/YYYY",
          dayFormat: "D",
          dateTimeFormat: "M/D/YYYY HH:mm:ss",
          monthFormat: "MMMM",
          monthBeforeYear: true,
          previousMonth: "Previous month (PageUp)",
          nextMonth: "Next month (PageDown)",
          previousYear: "Last year (Control + left)",
          nextYear: "Next year (Control + right)",
          previousDecade: "Last decade",
          nextDecade: "Next decade",
          previousCentury: "Last century",
          nextCentury: "Next century"
        },
        timePickerLocale: {
          placeholder: "Select time"
        },
        dateFormat: "YYYY-MM-DD",
        dateTimeFormat: "YYYY-MM-DD HH:mm:ss",
        weekFormat: "YYYY-wo",
        monthFormat: "YYYY-MM"
      };
    },
    '$store.state.isRefreshBlockList'() { //判断快照被克隆后，块设备列表重新获取
      this.getdata();
    },
    currentTabKey(newValue) {
      if (newValue == 'block') {
        this.getbasedata()
        this.getdata();
        this.getStrategy();
      }
    },

  },
  created() {
    const tags = localStorage.getItem('tags');
    if (tags.indexOf('D23') !== -1) {
      this.authArr.push('overview'); //概况
    }
    if (tags.indexOf('D4') !== -1) {
      this.authArr.push('block'); //块设备
    }
    if (tags.indexOf('D6') !== -1) {
      this.authArr.push('2'); // 回收站
    }
    if (tags.indexOf('D7') !== -1 || tags.indexOf('D22') !== -1) {
      this.authArr.push('iscsi'); //iscsi
    }
    if (tags.indexOf('D8') !== -1) {
      this.authArr.push('4'); //优先级策略
    }
    this.addListenerfun('block', this.getdata) //通知交互：监听变化 刷新
    this.addListener('block') //通知交互：监听变化 刷新
    this.handleRouteBack();
  },

  mounted() {
    // this.getbasedata()
    // this.getdata();
    // this.getStrategy();
  },

  beforeDestroy() {
    localStorage.removeItem('block_current_tab');
  },

  methods: {
    getbasedata() {
      //原来为 get  block/_info
      request('post', 'pool/getRbdInfoAll', {
        applications: ['rbd']
      }).then(res => {
        // console.log('创建块设备所属存储池',res)
        this.$store.commit('getblock', {
          baseblock: res.data
        })
      })
    },
    getdata() {
      this.loading = true
      request('get', 'block/').then(res => {
        // for(var i=0;i<res.data.length;i++){  //数据单位处理
        // 	res.data[i].size = this.bytesToSize(res.data[i].size)
        // 	res.data[i].num_objs = this.bytesToBs(res.data[i].num_objs)
        // 	res.data[i].obj_size = this.bytesToSize(res.data[i].obj_size)
        // 	res.data[i].disk_usage = this.bytesToSize(res.data[i].disk_usage)
        // 	res.data[i].total_disk_usage = this.bytesToSize(res.data[i].total_disk_usage)
        // }
        console.log('获取块设备', res)
        this.blockdata = res.data
        this.$store.commit('getblockdata', {
          blockdata: res.data,
        })
        if (this.$store.state.blockdata.length !== 0) {
          this.onerecord = this.$store.state.blockdata[this.num]
        }
      }).catch(err => {
        // this.$message.error(this.$t('Get-data-failed'))
      }).finally(() => {
        this.loading = false
      })
    },
    // getCheckboxProps(record){  //判断正在操作的状态，如果该条信息正在操作，则禁止其他操作
    //   return ({
    //     props: {
    //         disabled: record.status !== "normal",
    //       },
    //   })
    // },

    //获取策略
    getStrategy() {
      request('get', 'block/strategy/', {
        // params: { 
        // user_id: this.user_id
        // }
      }).then(res => {
        // console.log('块设备获取策略',res);
        this.strategyData = res.data;
      }).catch(err => {
        console.log(err);
      })
    },


    onSelect(record, selected, selectedRows) {
      this.tarparent = ''
      for (let i = 0; i < this.$store.state.blockdata.length; i++) {
        if (record.id == this.$store.state.blockdata[i].id) {
          this.num = i;
          if (item.parent !== null) {
            this.tarparent = this.$store.state.blockdata[i].parent
          }
        }
      }
      this.blockId = record.id;
      this.target = record.name;
      this.pool = record.pool_id;
      this.onerecord = record;
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      // this.target = selectedRowKeys.join(selectedRowKeys)
      // this.tarparent = ''
      // for(var i=0;i<this.$store.state.blockdata.length;i++){
      //   // if(this.target == this.$store.state.blockdata[i].key){
      //   if(selectedRow[0].id == this.$store.state.blockdata[i].id){
      //     // this.target = this.$store.state.blockdata[i].name
      //     // this.pool = this.$store.state.blockdata[i].pool_name
      //     // this.onerecord = this.$store.state.blockdata[i]
      //     this.num = i
      //     if(this.$store.state.blockdata[i].parent !== null){
      //       // this.tarparent = this.$store.state.blockdata[i].parent.snap_name
      //       this.tarparent = this.$store.state.blockdata[i].parent
      //     }
      //   }
      // }
      // this.target = selectedRow[0].name;
      // this.pool = selectedRow[0].pool_name;
      // this.onerecord = selectedRow[0];
      this.selectedRowKeys = selectedRowKeys
    },
    changemodal(val, isCancel) {
      this.create = val
      this.modify = val
      this.copy = val
      if (!isCancel) {
        this.getdata()
      }
    },
    resetflag(val) {
      this.getdata() //回收站恢复刷新块设备列表
    },
    cancelhandle(e) {
      this.trash = false
      this.spinning = false
      this.form.resetFields();
    },
    openmodal(name, record) {
      this.tarparent = '';
      for (let i = 0; i < this.$store.state.blockdata.length; i++) {
        if (record.id == this.$store.state.blockdata[i].id) {
          this.num = i;
          if (this.$store.state.blockdata[i].parent !== null) {
            this.tarparent = this.$store.state.blockdata[i].parent
          }
        }
      }

      this.blockId = record.id;
      this.target = record.name;
      this.pool = record.pool_id;
      this.onerecord = record;

      // if(this.$store.state.blockdata[this.num].status !== 'normal'){
      if (this.$store.state.blockdata[this.num].status) {
        this.$notification['error']({
          message: this.$t('Try-later')
        })
      } else {
        if (name == 'modify') {
          this.modify = true;
        } else if (name == 'copy') {
          this.copy = true;
        } else if (name == 'detach') {
          if (this.tarparent !== '') {
            this.detach();
          } else {
            this.$notification['error']({
              message: this.$t('Not-to-separate')
            })
          }
        }
        else if (name == 'delosd')
          this.delosd();
        else if (name == 'trash')
          this.trash = true;
      }
    },
    // openmodal(name){
    //     if(this.selectedRowKeys.length!=0){
    //       if(this.$store.state.blockdata[this.num].status !== 'normal'){
    //         this.$notification['error']({
    //           message: this.$t('Choose')+this.$t('Try-later')
    //         })
    //       }else{
    //         if(name=='modify') {
    //           this.modify = true
    //         }else if(name == 'copy') {
    //           this.copy = true
    //         }else if(name == 'detach') {
    //           if(this.tarparent !== ''){
    //             this.detach()
    //           }else{
    //             this.$notification['error']({
    //               message:this.$t('Not-to-separate')
    //             })
    //           }
    //         }
    //         else if(name == 'delosd')
    //           this.delosd()
    //         else if(name == 'trash')
    //           this.trash=true
    //         }
    //       }
    //     else{
    //       this.$notification['error']({
    //         message: this.$t('Choose')+this.$t('Operating-object')
    //       })
    //     }
    // },
    //块设备分离
    detach() {
      let _this = this
      this.$confirm({
        title: this.$t('Detach'),
        content: "块设备 【" + this.target + "】 从父节点分离！ 将会从父节点 【" + this.tarparent + "】 复制所有数据到块设备 【" + this.target + "】",
        cancelText: this.$t('Cancel'),
        okText: this.$t('Sure'),
        okType: 'danger',
        onOk() {
          _this.loading = true;
          // _this.$notification.open({
          //   message: _this.$t('Operation-prompt'),
          //   description: _this.$t('Block-device-detaching'),
          // });
          // _this.$axios({
          // 	  method: 'post',
          // 	  url: _this.allurl+'block/flatten',
          // 	  data: {
          // 	    // pool:_this.pool,
          // 	    // name:_this.target
          //       pool_id: _this.onerecord.pool_id,
          //       id: _this.onerecord.id,
          //       pool_name: _this.onerecord.pool_name,
          //       block_name: _this.onerecord.name
          // 	  }
          // 	})
          request('post', 'block/flatten', {
            pool_id: _this.onerecord.pool_id,
            id: _this.onerecord.id,
            pool_name: _this.onerecord.pool_name,
            block_name: _this.onerecord.name
          })
            .then(res => {
              _this.model(res.data.id) //返回模板
              _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              // _this.gettask()  //任务栏信息
              _this.getdata();
            })
        },
        onCancel() {
          return;
        },
      })
    },

    // 删除块
    delosd() {
      let _this = this
      this.$confirm({
        title: this.$t('Delete'),
        content: this.$t('Sure-to-del') + ": " + this.target + ' ？',
        cancelText: this.$t('Cancel'),
        okText: this.$t('Sure'),
        okType: 'danger',
        onOk() {
          // _this.$axios({
          // 	  method: 'delete',
          // 	  url: _this.allurl+'block/',
          // 	  data: {
          // 	    // pool:_this.pool,
          // 	    // name:_this.target
          //       id: _this.onerecord.id,
          //       pool_id: _this.onerecord.pool_id,
          //       name: _this.onerecord.name,
          //       pool_name: _this.onerecord.pool_name,
          // 	  }
          // 	})
          request('DELETE', 'block/', {
            id: _this.onerecord.id,
            pool_id: _this.onerecord.pool_id,
            name: _this.onerecord.name,
            pool_name: _this.onerecord.pool_name,
          })
            .then(res => {
              _this.model(res.data.id) //返回模板
              _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              // _this.gettask()  //任务栏信息
              _this.target = ''
              _this.getdata()
              _this.selectedRowKeys = []; // 将选择的项清空
              _this.$store.commit('toGetBlockData', !_this.$store.state.isBlockListChange);
            })
        },
        onCancel() {
          return;
        }
      })
    },
    //放入回收站
    trashsub(e) {
      this.trashflag = false
      e.preventDefault();
      this.form.validateFields((err, value) => {
        if (!err) {
          this.spinning = true
          this.gettime()
          // this.$axios({
          //   method: 'put',
          //   url: this.allurl+'block/trash/',
          //   data: {
          //     // pool:this.pool,
          //     // name:this.target,
          //     // end:this.delay
          //     pool_id: this.onerecord.pool_id,
          //     image_id: this.onerecord.id,
          //     end_time: this.delay,
          //     pool_name: this.onerecord.pool_name,
          //     block_name: this.onerecord.name
          //   }
          // })
          request('put', 'block/trash/', {
            pool_id: this.onerecord.pool_id,
            image_id: this.onerecord.id,
            end_time: this.delay,
            pool_name: this.onerecord.pool_name,
            block_name: this.onerecord.name
          })
            .then(res => {
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              // this.gettask()  //任务栏信息
              this.spinning = false
              this.trash = false
              this.trashflag = true  //更新回收站的标志
              this.form.resetFields();
              this.getdata()
              this.$store.commit('toGetBlockData', !this.$store.state.isBlockListChange);
            })
        }
      })
    },
    Changedate(value, dateString) {
      this.showtime = dateString
    },
    gettime() {
      let end = new Date(this.showtime)
      let s2 = end.getTime()
      this.delay = s2 / 1000
    },
    handleSearch(selectedKeys, confirm) {
      confirm()
      this.searchText = selectedKeys[0]
    },
    handleReset(clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    tabsChange(key) {
      this.currentTabKey = key;
      localStorage.setItem('block_current_tab', JSON.stringify(key));
    },

    //导出报表
    async exportReport() {
      // this.exportReportVisible = true;
      this.loadingExport = true;
      const res = await this.$api.blockOverview.exportBlockInfoRequest({ responseType: 'blob' });
      // console.log('导出报表', res)
      if (res.data) {
        downloadFile(res.data, 'application/vnd.ms-excel', 'reportInfo.xlsx');
        this.$message.success(this.$t('Export-ok'));
      } else {
        this.$message.success(this.$t('Export-no'));
      }
      this.loadingExport = false;
    },

    //关闭导出报表弹窗
    closeExport() {
      this.exportReportVisible = false;
    },

    //打开导入块设备弹窗
    handleImportBlock() {
      this.importBlockVisible = true;
    },

    //关闭导入块设备弹窗
    closeImport() {
      this.importBlockVisible = false;
    },

    // // 获取当前块设备的信息
    // async getNowBlockInfo(currentBlock) {
    //   const params = {
    //     pool_id: currentBlock.pool_id, // 存储池的id号
    //     image_id: currentBlock.id  // 块设备id号
    //   };
    //   const res = await this.$api.blockInfo.getBlockInfoRequest(params);
    //   this.infoSpinning = false;
    //   // if(re)
    //   console.log('当前块设备的信息：', res)
    // },

    //跳转到块设备详情页
    async showBlockDetail(record) {
      console.log(record)
      this.$router.push({
        path: "/BlockDetail",
        query: {
          targetBlock: encodeURIComponent(JSON.stringify(record))
        }
      })
    },

    //监听块设备详情返回
    handleRouteBack() {
      if (this.$route.params.tab !== undefined) {
        this.defaultActiveKey = this.$route.params.tab;
        this.currentTabKey = this.$route.params.tab;
        localStorage.setItem('block_current_tab', JSON.stringify(this.$route.params.tab));
      }
      else {
        // this.defaultActiveKey = 'overview';
        // this.currentTabKey = 'overview';
        this.currentTabKey = JSON.parse(localStorage.getItem('block_current_tab')) || 'overview';
        this.defaultActiveKey = JSON.parse(localStorage.getItem('block_current_tab')) || 'overview';
      }
    },

    // 容量排序比较
    sizeCompare(a, b) {
      return sizeCompare(a, b)
    },

    // ip地址排序比较
    sortIp(a, b) {
      return sortIp(a, b)
    },
  }
};
</script>

<style scoped>
.export-btn {
  width: 100px;
}

.export-icon {
  margin-right: 5px;
}

.out-operation-icon {
  margin-right: 5px;
}

.menu-item-icon {
  color: var(--themeColor);
  margin-right: 5px;
}

.jump-text {
  color: var(--themeColor);
  cursor: pointer;
}

::v-deep.ant-tabs-bar {
  margin-bottom: 0;
}

::v-deep.ant-table-body {
  overflow-x: auto !important;
}
</style>
